<template>
  <div ref="chart"  :style="chartStyle">
    <q-img v-if='!config.viewId'
    :style="imageStyle"
    src="/img/bi/empty-chart.png"
    />
  </div>
</template>

<script>
import echarts from 'echarts';
import { runFnInVm } from './widgets/vm';

require('echarts/theme/shine');
require('echarts-wordcloud');

export default {
  name: 'chart',
  props: {
    config: {
      required: true,
      default: () => {},
    },
    chartStyle: {
      require: false,
      type: Object,
      default: () => ({
        height: '100%',
        position: 'absolute',
        width: '100%',
        top: '0px',
        bottom: '0px',
        left: '0px',
      }),
    },
  },
  components: {
  },
  data() {
    return {
      chart: null,
      loading: false,
      imageStyle: {
        width: '100%',
        height: '100%',
        objectFit: 'cover',
      },
    };
  },
  computed: {
  },
  watch: {
    config: {
      deep: true,
      handler() {
        if (this.config.needResize) {
          this.config.needResize = false;
          this.handleResize();
        }
        this.renderChart();
      },
    },
  },
  methods: {
    handleResize() {
      if (this.chart) {
        this.chart.resize();
      }
    },
    getOptions(code) {
      const result = runFnInVm(code, echarts);
      return result.value;
    },
    renderChart() {
      if (!this.chart && this.$refs.chart) {
        this.chart = echarts.init(this.$refs.chart, this.config.theme);
      }
      if (this.config.code) {
        const option = this.getOptions(this.config.code);
        this.chart.clear();
        this.chart.setOption(option);
        setTimeout(() => {
          this.chart.resize();
        }, 100);
      }
    },
  },
  mounted() {
    this.renderChart();
  },
  created() {
  },
  beforeDestroy() {
  },
};
</script>

<style lang="stylus">
</style>
